#include <sys/ipc.h>
#include <sys/shm.h>
#include<iostream>
#include"log.hpp"
#define SIZE_SHM 4096
using namespace std;
const string pathname="/home/user1";
int proj_id=1;
Log log;
key_t GetKey()
{
    
    key_t key=ftok(pathname.c_str(),proj_id);
    if(key<0)
    {
        log.logmessage(Fatal,"ftok 错误: %s",strerror(errno));
        exit(errno);
    }
    log.logmessage(Info,"key创建成功 key:%d",key);
    return key;
}

int GetShareMemHelper(int flag)
{
    int shmid=shmget(GetKey(),SIZE_SHM,flag);
    if(shmid<0)
    {
        log.logmessage(Fatal,"shmget 错误：%s",strerror(errno));
        exit(errno);
    }
    log.logmessage(Info,"申请共享内存成功 shmid:%d",shmid);
    return shmid;
}


int GetShmid()
{
    return GetShareMemHelper(IPC_CREAT);

}

int CreatShmid()
{
    return GetShareMemHelper(IPC_CREAT|IPC_EXCL|0666);
}

void DeletShm(int shmid)
{
     int ret=shmctl(shmid,IPC_RMID,nullptr);
    if(ret<0)
    {
        log.logmessage(Fatal,"共享内存删除失败");
    }
    log.logmessage(Info,"共享内存删除成功");
}

void  CreatChannel()
{
     int ret=mkfifo(FIFO_FILE,MODE);
    if(ret<0)
    {
        log.logmessage(Error,"%s文件已存在退出码: %d",FIFO_FILE,FILE_EXIIED);
        exit(FILE_EXIIED);
    }   
}

int OpenChannel(int _oflag)
{
    int fd=open(FIFO_FILE,_oflag);
    std::cout<<"open mkfifo文件成功"<<std::endl;
    log.logmessage(Info,"open mkfifo文件成功");
    return fd;

}

void DeletChannel()
{
    int ret=unlink(FIFO_FILE);
    if(ret<0)
    {
        log.logmessage(Error,"%S delet failuer",FIFO_FILE);
        exit(errno);
    }

}



